package com.zj.log.controller;

import com.zj.log.client.UserClient;
import com.zj.log.common.User;
import com.zj.log.component.UserRoleAuthentication;
import com.zj.log.domain.MsgContent;
import com.zj.log.domain.MsgUser;
import com.zj.log.enums.CommonEnum;
import com.zj.log.enums.RoleEnum;
import com.zj.log.repository.MsgContentRepository;
import com.zj.log.repository.MsgUserRepository;
import com.zj.log.util.ResultVoUtil;
import com.zj.log.vo.MsgContentVo;
import com.zj.log.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Auther: zj
 * @Date: 2019/2/25 17:44
 * @Description:
 */
@RestController
public class MsgController {
    @Autowired
    UserRoleAuthentication userRoleAuthentication;
    @Autowired
    UserClient userClient;
    @Autowired
    MsgContentRepository msgContentRepository;
    @Autowired
    MsgUserRepository msgUserRepository;

    /**
     * 发消息 管理员权限
     * @param request
     * @param message
     * @return
     */
    @PostMapping("/sendMsg")
    @Transactional
    public ResultVo sendMsg(HttpServletRequest request,
                            @RequestParam("message") String message) {

        //鉴权
        String username = userRoleAuthentication.getUsernameAndAutenticateUserRoleFromRequest( request, RoleEnum.Admin.getMessage() );
        if (Objects.equals( username, CommonEnum.FALSE.getMessage())) {
            return ResultVoUtil.error();
        }

        Date date = new Date(  );//获取当前时间，Date型

        //将当前时间转换为从1970年1月1日到现在所经历的毫秒数
        Long dateLong = date.getTime();				// Date型转换成Long型毫秒数，用于计算
        System.out.println("毫秒数dateLong:" + dateLong);

        MsgContent msgContent = new MsgContent( null,message,dateLong );
        msgContentRepository.save( msgContent );//保存到数据库

        List<User> userList= userClient.getAllUser();


        for (User user:userList) {
            MsgUser msgUser = new MsgUser( msgContent.getId(),null,user.getId(), 0);
            msgUserRepository.save( msgUser );
        }

        return ResultVoUtil.success("发送消息成功！");
    }


    /**
     * 获取当前用户的所有收到的消息
     * @param request
     * @return
     */
    @GetMapping("/getSelfUserMsg")
    public ResultVo getSelfUserMsg(HttpServletRequest request) {
        //鉴权
        String username = userRoleAuthentication.getUsernameAndAutenticateUserRoleFromRequest( request, RoleEnum.User.getMessage() );
        if (Objects.equals( username, CommonEnum.FALSE.getMessage())) {
            return ResultVoUtil.error();
        }
        User user=userClient.getUserByUsername( username );

        List<MsgUser> msgUserList = msgUserRepository.findAllByUserId( user.getId() );

        List<MsgContentVo>msgContentVoList = new ArrayList<>(  );
        for (MsgUser msgUser:msgUserList) {

            MsgContent msgContent =msgContentRepository.findOneById( msgUser.getMsgId() );
            Date date1 = new Date(msgContent.getCreateDate());//Long型毫秒数转换为Date型
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String date2 = df.format(date1);// //Date型 转换成String型
            MsgContentVo msgContentVo =new MsgContentVo( msgContent.getId(),msgContent.getTitle(),msgContent.getMessage(),date2);
            msgContentVoList.add( msgContentVo );
        }
        return ResultVoUtil.success(msgContentVoList);
    }

    /**
     * 获取当前用户的未读消息
     * @param request
     * @return
     */
    @GetMapping("/getSelfUserMsgWithoutReading")
    public ResultVo getSelfUserMsgWithoutReading(HttpServletRequest request) {
        //鉴权
        String username = userRoleAuthentication.getUsernameAndAutenticateUserRoleFromRequest( request, RoleEnum.User.getMessage() );
        if (Objects.equals( username, CommonEnum.FALSE.getMessage())) {
            return ResultVoUtil.error();
        }
        User user=userClient.getUserByUsername( username );

        List<MsgUser> msgUserList = msgUserRepository.findAllByUserIdAndState( user.getId(),0);

        List<MsgContentVo>msgContentVoList = new ArrayList<>(  );
        for (MsgUser msgUser:msgUserList) {

            MsgContent msgContent =msgContentRepository.findOneById( msgUser.getMsgId() );
            Date date1 = new Date(msgContent.getCreateDate());//Long型毫秒数转换为Date型
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String date2 = df.format(date1);// //Date型 转换成String型
            MsgContentVo msgContentVo =new MsgContentVo( msgContent.getId(),msgContent.getTitle(),msgContent.getMessage(),date2);
            msgContentVoList.add( msgContentVo );
        }
        return ResultVoUtil.success(msgContentVoList);
    }


    /**
     * 获取当前用户的已读消息
     * @param request
     * @return
     */
    @GetMapping("/getSelfUserMsgRead")
    public ResultVo getSelfUserMsgRead(HttpServletRequest request) {
        //鉴权
        String username = userRoleAuthentication.getUsernameAndAutenticateUserRoleFromRequest( request, RoleEnum.User.getMessage() );
        if (Objects.equals( username, CommonEnum.FALSE.getMessage())) {
            return ResultVoUtil.error();
        }
        User user=userClient.getUserByUsername( username );

        List<MsgUser> msgUserList = msgUserRepository.findAllByUserIdAndState( user.getId(),1);

        List<MsgContentVo>msgContentVoList = new ArrayList<>(  );
        for (MsgUser msgUser:msgUserList) {
            MsgContent msgContent =msgContentRepository.findOneById( msgUser.getMsgId() );
            Date date1 = new Date(msgContent.getCreateDate());
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date2 = df.format(date1);
            MsgContentVo msgContentVo =new MsgContentVo( msgContent.getId(),msgContent.getTitle(),msgContent.getMessage(),date2);
            msgContentVoList.add( msgContentVo );
        }
        return ResultVoUtil.success(msgContentVoList);
    }

    /**
     * 标记当前用户的消息为已读
     * @param request request
     * @return
     */
    @GetMapping("/markUserMsgRead")
    public ResultVo markUserMsgRead(HttpServletRequest request,
                                    @RequestParam("msgId") Integer msgId) {
        //鉴权
        String username = userRoleAuthentication.getUsernameAndAutenticateUserRoleFromRequest( request, RoleEnum.User.getMessage() );
        if (Objects.equals( username, CommonEnum.FALSE.getMessage())) {
            return ResultVoUtil.error();
        }
        User user=userClient.getUserByUsername( username );

        MsgUser msgUser =msgUserRepository.findOneByMsgIdAndUserId( msgId ,user.getId());
        msgUser.setState( 1 );
        msgUserRepository.save( msgUser );

        return ResultVoUtil.success("消息标记已读成功！");

    }



}
